package app.keter.secruity;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Record r = Db.findFirst("select id,username,password,status from org_user where username=?",username);
        if(r==null){
            throw new UsernameNotFoundException("username not found");
        }
        if(r.getInt("status")==1){
            throw new LockedException("用户锁定!");
        }
        if(r.getInt("status")==2){
            throw new DisabledException("用户禁用!");
        }
        List<Record> roles = Db.find(
                "select r.id,r.name from org_role r ,org_user_role ur "
                        + "where ur.user_id=? and ur.role_id=r.id"
                ,r.getInt("id")
        );
        UserDetails userDetails = new JwtUserDetails(String.valueOf(r.getInt("id")),username,r.getStr("password"),getAuthoritiesFromRoles(roles));
        return userDetails;
    }

    private Collection<? extends GrantedAuthority> getAuthoritiesFromRoles(List<Record> roles){
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>(roles.size());
        for (Record record : roles) {
            authorities.add(new SimpleGrantedAuthority(record.getStr("name")));
        }
        return authorities;
    }
}
